import React, { useState } from 'react';
import Modal from 'react-modal';
import './remark.css'; // 引入CSS文件

// 设置appElement，这是Modal需要渲染到的DOM元素
// 假设你的React根元素的id为'root'
Modal.setAppElement('#root');

// 定义评论的接口类型
interface Comment {
  id: number;       // 评论的唯一标识符
  text: string;     // 评论的内容
  replies?: Comment[]; // 可选的回复数组
}

// 创建一个功能组件来实现评论功能
const CommentsComponent: React.FC = () => {
  // 使用useState来管理弹出框的状态
  const [isCommentBoxOpen, setIsCommentBoxOpen] = useState(false); // 是否显示评论框
  // 存储所有的评论
  const [comments, setComments] = useState<Comment[]>([]);
  // 当前正在编辑的评论的文本
  const [newCommentText, setNewCommentText] = useState('');
  // 当前选中的评论ID，用于编辑操作
  const [selectedCommentId, setSelectedCommentId] = useState<number | null>(null);
  // 当前回复的目标评论ID及其父评论ID
  const [replyingTo, setReplyingTo] = useState<{ commentId: number, parentId: number | null } | null>(null);

  // 添加新评论
  const addNewComment = () => {
    const newComment: Comment = {
      id: Date.now(), // 使用当前时间戳作为唯一ID
      text: newCommentText, // 新评论的内容
    };
    setComments([...comments, newComment]);
    setNewCommentText(''); // 清空输入框
  };

  // 编辑评论
  const editComment = (id: number, newText: string) => {
    const updatedComments = comments.map(comment =>
      comment.id === id ? { ...comment, text: newText } : comment
    );
    setComments(updatedComments);
    setSelectedCommentId(null);
    setNewCommentText(''); // 清空输入框
  };

  // 删除评论
  const deleteComment = (id: number) => {
    const updatedComments = comments.filter(comment => comment.id !== id);
    setComments(updatedComments);
  };

  // 回复评论
  const replyToComment = (parentId: number, commentId: number) => {
    const newReply: Comment = {
      id: Date.now(),
      text: newCommentText,
    };
    const updatedComments = comments.map(comment => {
      if (comment.id === parentId) {
        return {
          ...comment,
          replies: [...(comment.replies || []), newReply],
        };
      }
      return comment;
    });
    setComments(updatedComments);
    setNewCommentText(''); // 清空输入框
    setReplyingTo(null);
  };

  // 处理输入框内容变化
  const handleInputChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
    setNewCommentText(event.target.value);
  };

  // 切换弹出框的显示状态
  const toggleCommentBox = (commentId?: number, parentId?: number) => {
    if (commentId !== undefined) {
      setReplyingTo({ commentId, parentId });
    } else {
      setReplyingTo(null);
    }
    // 只有在没有传递commentId的情况下才切换弹出框状态
    if (commentId === undefined) {
      setIsCommentBoxOpen(!isCommentBoxOpen);
    }
  };

  // 加载评论文本到输入框
  const loadCommentForEdit = (commentId: number) => {
    const commentToEdit = comments.find(comment => comment.id === commentId);
    if (commentToEdit) {
      setNewCommentText(commentToEdit.text);
    }
    setSelectedCommentId(commentId);
    setIsCommentBoxOpen(true); // 显示弹出框
  };

  // 提交评论或编辑评论或回复评论
  const handleCommentSubmit = () => {
    if (selectedCommentId !== null) {
      editComment(selectedCommentId, newCommentText);
    } else if (replyingTo !== null) {
      replyToComment(replyingTo.parentId ?? 0, replyingTo.commentId);
    } else {
      addNewComment();
    }
    // 不再关闭弹出框
  };

  // 渲染评论列表
  const renderComments = (comments: Comment[], level: number = 0): JSX.Element[] => {
    return comments.map(comment => (
      <li key={comment.id} className={`comment-item level-${level}`}>
        <div className="comment-text">{comment.text}</div>
        <div className="comment-actions">
          <button onClick={() => loadCommentForEdit(comment.id)}>编辑</button>
          <button onClick={() => deleteComment(comment.id)}>删除</button>
          <button onClick={() => toggleCommentBox(comment.id, comment.id)}>回复</button>
        </div>
        {comment.replies && comment.replies.length > 0 && (
          <>
            <ul>{renderComments(comment.replies, level + 1)}</ul>
          </>
        )}
      </li>
    ));
  };

  return (
    <div>
      <button onClick={() => toggleCommentBox()}>评论</button>
      <Modal 
        isOpen={isCommentBoxOpen}
        onRequestClose={() => setIsCommentBoxOpen(false)}
        contentLabel="评论"
        style={{
          overlay: {
            position: 'fixed',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            backgroundColor: 'rgba(0, 0, 0, 0.75)',
            zIndex: 1000,
          },
          content: {
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            border: '1px solid #ccc',
            background: '#fff',
            overflow: 'auto',
            WebkitOverflowScrolling: 'touch',
            borderRadius: '10px',
            padding: '20px',
            width: '300px', // 设置宽度
            height: 'auto', // 高度根据内容自动调整
            zIndex: 1001, // 确保内容层在背景之上
          },
        }}
      >
        <textarea
          value={newCommentText}
          onChange={handleInputChange}
          placeholder="写下你的评论..."
        />
        <button onClick={handleCommentSubmit}>提交</button>
        <ul className="comments-list">
          {renderComments(comments)}
        </ul>
      </Modal>
    </div>
  );
};

export default CommentsComponent;